/**
 * Created by shandianhaizan on 16/6/30.
 */
define([], function () {

    function _controller($scope, $routeParams, $location, $timeout, httpService) {


        var model ="Group";
        var attrs = {"name":"分组名","discount":"折扣大小"};
        $scope.showAttrs = [];
        angular.forEach(attrs, function(v, k){
            $scope.showAttrs.push({"zhCn":v, "en": k });
        });

        $scope.showLoading();


        $scope.editObject = function(arg_o){
            $scope.editGroup = {};
            if(arg_o)  $scope.editGroup =  angular.copy(arg_o);
        };


        $scope.validation = function(group){

            if(!group.discount || group.discount <0 || group.discount >10) {
                return {success:false, msg:"折扣必须介于0到10之间且最多两位小数"};
            }
            if(group.discount){
                var l = group.discount.toString().split(".")
                if(l[1] &&  l[1].length>2) {
                    return {success:false, msg:"折扣必须介于0到10之间且最多两位小数"};
                }
            }
            return {success:true};
        };


        $scope.save = function () {
            $scope.$broadcast('show-errors-check-validity');
            var validation = $scope.validation($scope.editGroup);
            if(!validation.success) return $scope.msg.show(validation.msg);
            if (!$scope.userForm.$valid) return;
            httpService.save(model, $scope.editGroup).then(function (data) {
                $('#myModal').modal('hide');
                $scope.msg.show(data);
                $scope.getAll();
            });
        };


        $scope.getAll = function () {
            httpService.get(model, {all:true, sort:"createdAt"}).then(function (data) {
                $scope.models = data.data.data;
                $scope.hideLoading();
            });

        };

        $scope.showRemove = function(m){
            $scope.deleteName = m.name;
            $scope.deleteObject = m;
        };


        $scope.remove = function(m){
            httpService.del(model, m.objectId).then(function (data) {
                httpService.removeParent(model, m.objectId).then(function (data) {
                    $scope.msg.show(data);
                    if($scope.isHandleSuccess(data)){
                        $scope.getAll();
                    }
                });
            });
        };

        $scope.getAll();

    }

    return _controller;
});

